<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>debouncePromise</title>
</head>

<body>
    <div>打开浏览器控制台查看结果</div>
    <script>
        const debouncePromise = (handler, ms) => {
            let timer = null;
            const pending = [];
            return (...args) =>
                new Promise((resolve, reject) => {
                    clearTimeout(timer);
                    timer = setTimeout(() => {
                        const currentPending = [...pending];
                        pending.length = 0;
                        Promise.resolve(handler.apply(this, args)).then(
                            data => {
                                currentPending.forEach(({ resolve: res }) => res(data));
                            },
                            error => {
                                currentPending.forEach(({ reject: rej }) => rej(error));
                            }
                        );
                    }, ms);
                    pending.push({ resolve, reject });
                });
        };
        const fn = arg =>
            new Promise(resolve => {
                setTimeout(resolve, 1000, ['resolved', arg]);
            });
        const debounced = debouncePromise(fn, 200);
        debounced('foo').then(console.log);
        debounced('bar').then(console.log);
    </script>
</body>

</html>